<?php
namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;
use think\helper\Str;
use think\exception\ValidateException;


// 推送记录统计
class PushRecord extends BaseController
{
    public function index()
    {
        return View::fetch();
    }


    public function load(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return json(['code' => 500, 'data' => '', 'msg' => '无操作权限']);
        }

        $get = $request->get();
        $where = [];

        if (isset($get['tree_select_nodeId'])) {
            if (!empty($get['tree_select_nodeId'])) {
                $department = $get['tree_select_nodeId'];
                $arr = get_children($department, 1);
                $arr[] = $department;
                $department = implode('|', $arr);
                $where[]  = ['', 'EXP', Db::raw("CONCAT(',',a.department,',') REGEXP concat(',(',replace('".$department."',',','|'),'),')")];
            }
        }

        if (isset($get['type'])) {
            if (!empty($get['type'])) {
                $where[] = ['a.type', 'like', '%'.$get['type'].'%'];
            }
        }

        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $t = explode(' - ', $get['time']);
                $where[] = ['a.add_time', 'between', [strtotime($t[0]), strtotime($t[1])+86399]];
            }
        }

        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['b.name|b.userid', 'like', '%'.$get['key'].'%'];
            }
        }


        $total = Db::table('o_push_record')
            ->alias('a')
            ->join('o_members b', 'b.userid=a.userid')
            ->where($where)
            ->count();

        $rows = Db::table('o_push_record')
            ->alias('a')
            ->join('o_members b', 'b.userid=a.userid')
            ->where($where)
            ->order('a.id', 'desc')
            ->field('a.type, a.errcode, a.errmsg, a.add_time, a.class_id, b.userid, b.name, b.department_name, b.division')
            ->page($get['page'], $get['limit'])
            ->select()->toArray();
        foreach ($rows as &$v) {

            if ($v['class_id'] == 0) {
                $v['title'] = '';
                $v['course_name'] = '';
                $v['start_time'] = '';
            } else {
                $class = Db::name('classes')->where(array('id'=>$v['class_id']))->field('id, title, start, courseid')->find();
                $course = Db::name('course')->where(array('courseid'=>$class['courseid']))->field('seminar, e_seminar')->find();
                $course_name = $course['seminar'] == '' ? $course['e_seminar']:$course['seminar'];
                $v['title'] = $class['title'];
                $v['course_name'] = $course_name;
                $v['start_time'] = date('Y-m-d H:i', $class['start']);
            }

            $count = mb_strlen($v['userid']);
            if ($count == 6) {
                if (is_numeric($v['userid'])) {
                    $v['userid'] = '00'.$v['userid'];
                }
            }
        }
        $data = array(
            'code'=> 0,
            'msg'=> '',
            'count' => $total,
            'data'=> $rows
        );
        return json($data);
    }



    // 数据导出
    public function export(Request $request)
    {
        if(!check_jurisdiction(session('admin_auth.role_id'), $this->control, $this->action)) {
            return $this->outputAjax('无操作权限');
        }


        $get = $request->get();
        $where = [];

        if (isset($get['tree_select_nodeId'])) {
            if (!empty($get['tree_select_nodeId'])) {
                $department = $get['tree_select_nodeId'];
                $arr = get_children($department, 1);
                $arr[] = $department;
                $department = implode('|', $arr);
                $where[]  = ['', 'EXP', Db::raw("CONCAT(',',a.department,',') REGEXP concat(',(',replace('".$department."',',','|'),'),')")];
            }
        }

        if (isset($get['type'])) {
            if (!empty($get['type'])) {
                $where[] = ['a.type', 'like', '%'.$get['type'].'%'];
            }
        }

        if (isset($get['time'])) {
            if (!empty($get['time'])) {
                $t = explode(' - ', $get['time']);
                $where[] = ['a.add_time', 'between', [strtotime($t[0]), strtotime($t[1])+86399]];
            }
        }

        if (isset($get['key'])) {
            if (!empty($get['key'])) {
                $where[] = ['b.name|b.userid', 'like', '%'.$get['key'].'%'];
            }
        }

        set_time_limit(0);
        //设置程序运行内存
        ini_set('memory_limit', '4096M');

        $fileName = '推送记录数据'.date('Ymd', time());
        header('Content-Encoding: UTF-8');
        header("Content-type:application/vnd.ms-excel;charset=UTF-8");
        header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');


        //打开php标准输出流
        $fp = fopen('php://output', 'a');

        //添加BOM头，以UTF8编码导出CSV文件，如果文件头未添加BOM头，打开会出现乱码。
        fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));


        //添加导出标题
        fputcsv($fp, ['工号', '姓名', 'Division', '部门', '推送类型', '状态', '推送时间', '班级名称', '课程名', '开班时间']);

        //链接数据库
        $total = Db::table('o_push_record')
            ->alias('a')
            ->join('o_members b', 'b.userid=a.userid')
            ->where($where)
            ->count();

        $nums = 2000; //每次导出数量
        $step = ceil($total/$nums); //循环次数

        for($i = 0; $i < $step; $i++) {
            $start = $i * $nums;
            $rows = Db::table('o_push_record')
                ->alias('a')
                ->join('o_members b', 'b.userid=a.userid')
                ->where($where)
                ->order('a.id', 'desc')
                ->field('a.type, a.errcode, a.errmsg, a.add_time, a.class_id, b.userid, b.name, b.department_name, b.division')
                ->limit($start, $nums)
                ->select()
                ->toArray();
            foreach ($rows as $v) {
                switch ($v['type']) {
                    case 1:
                        $push_type_name = '开课提醒';
                        break;
                    case 2:
                        $push_type_name = '签到提醒';
                        break;
                }
                if ($v['errcode'] == 0) {
                    $errcode = '成功';
                } else {
                    $errcode = '失败';
                }

                if ($v['class_id'] == 0) {
                    $title = '';
                    $course_name = '';
                    $start_time = '';
                } else {
                    $class = Db::name('classes')->where(array('id'=>$v['class_id']))->field('id, title, start, courseid')->find();
                    $course = Db::name('course')->where(array('courseid'=>$class['courseid']))->field('seminar, e_seminar')->find();
                    $course_name = $course['seminar'] == '' ? $course['e_seminar']:$course['seminar'];
                    $title = $class['title'];
                    $course_name = $course_name;
                    $start_time = date('Y-m-d H:i', $class['start']);
                }

                $count = mb_strlen($v['userid']);
                if ($count == 6) {
                    if (is_numeric($v['userid'])) {
                        $userid = "'00".$v['userid'];
                    } else {
                        $userid = $v['userid'];
                    }
                } else {
                    $userid = $v['userid'];
                }

                $arr = [
                    $userid,
                    $v['name'],
                    $v['division'],
                    $v['department_name'],
                    $push_type_name,
                    $errcode,
                    date('Y-m-d H:i',$v['add_time']),
                    $title,
                    $course_name,
                    $start_time
                ];
                fputcsv($fp, $arr);
            }
            //每1千条数据就刷新缓冲区
            ob_flush();
            flush();
        }
    }
}